package com.threegroup.admin.controller;

import com.threegroup.admin.common.properties.MinioProperties;
import com.threegroup.admin.common.utils.MinioUtils;
import com.threegroup.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.UUID;

@RestController
@RequestMapping("/takeout/common")
@Slf4j
public class CommonController {

    @Resource
    private MinioProperties minioProperties;

    @Resource
    private MinioUtils minioUtils;

    @PostMapping("/upload")
    public Result upload(MultipartFile file) {

        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");

        String extension = originalFilename.substring(index - 1);
        String fileName = UUID.randomUUID().toString() + extension;

        try {

            // 将图片上传到Minio
            minioUtils.upload(file, fileName, minioProperties.getBucketName());
            
        } catch (Exception e) {
            log.error("图片上传失败! {}", e);
            return new Result<String>().error("图片上传失败");
        }

        return new Result<String>().ok(fileName);
    }

}
